global with sharing class buttonExecutionClass
{
     
      //For Validation of Contact Creation Process Button For Tracking...
     Webservice static string slaApplicationTrackingButton(ID objectId, string processName)
     {
        try
         {
             List<SLA__c> slaList = null;
             if(processName == 'Application')
                 slaList = new List<SLA__c>([SELECT ID, isCompleted__c, Actual_End_Date_Time__c, Actual_Start_Date_Time__c, Amendment__c, Application_Type__c, Expected_End_Date__c, License__c,isCancelled__c, Process_Type__c, SLA_Hours__c, Status__c,Application__c ,Tracking__c, Tenancy_Contract__c FROM SLA__c where Application__c =: objectId AND isCompleted__c =: false AND isCancelled__c =: false AND Actual_End_Date_Time__c =: null ORDER BY CreatedDate ]);
             else
                 slaList = new List<SLA__c>([SELECT ID, isCompleted__c, Actual_End_Date_Time__c, Actual_Start_Date_Time__c, Amendment__c, Application_Type__c, Expected_End_Date__c, License__c,isCancelled__c, Process_Type__c, SLA_Hours__c, Status__c,Application__c ,Tracking__c, Tenancy_Contract__c FROM SLA__c where Tracking__c =: objectId AND isCompleted__c =: false AND isCancelled__c =: false AND Actual_End_Date_Time__c =: null ORDER BY CreatedDate ]);
             if(slaList.size() > 0)
             {
                 for(SLA__c slaObject : slaList )
                 {
                
                    //Putting the Actual_End_Date_Time__c End Date of SLA...
                    slaObject.Actual_End_Date_Time__c = DateTime.Now();
                    slaObject.isCompleted__c =true;
                    
                 }
             }
             
             //Upserting the SLA List...
             if(slaList.size() > 0)
                 upsert slaList;
             
             //returning the values...
             return 'Success';
                          
         }
         catch(System.Exception err)
         {
             //return err.getMessage(); 
             return 'Error => '+ err.getMessage();
         }
                        
     }
     
     //For Validation of Contact Creation Process Button For Tracking...
     Webservice static string validateContactCreationTrackingButton(ID trackingId)
     {
        try
         {
             List<Receipt__c> receiptObjectList = new List<Receipt__c>([SELECT Id,Name,is_Cancelled_Receipt__c,Tracking__c,paymentConfirmationFlag__c FROM Receipt__c where is_Cancelled_Receipt__c =: false AND Tracking__c =: trackingId]);
             
             for(Receipt__c receiptObject :receiptObjectList)
             {
                
                if(receiptObject.paymentConfirmationFlag__c == false)
                    return 'Receipt '+ receiptObject.Name + ' is not confirmed, please mark it as confirmed to continue';
             }
                    
             if(receiptObjectList.size() == 0)
             {
                return 'Please create a valid receipt for this tracking to continue';   
             }
             
             //returning the values...
             return 'Success';
                          
         }
         catch(System.Exception err)
         {
             //return err.getMessage(); 
             return 'Error => '+ err.getMessage();
         }
                        
     }
     //For Validation of Amendment Process  Button....
     Webservice static string passwordGenerationButton(ID accountId)
     {
         try
         {
             List<Account> accountObject = new List<Account>([SELECT isPasswordGenerated__c,Temp_Password__c FROM Account where ID =: accountId]);
             
             if(accountObject.size() > 0)
             {
                 Blob blobKey = crypto.generateAesKey(128);
                 String key = EncodingUtil.convertToHex(blobKey);
                 System.debug('The User Key Becomes => '+key);
                 //accountObject[0].Temp_Password__c = key.substring(0,8);
                 accountObject[0].isPasswordGenerated__c = true;
                 
                 
             }
             //Now update the Account...
                 
             if(accountObject.size() > 0)
                 update accountObject;
             
             //returning the values...
             return 'Success';  
         }
         catch(System.Exception err)
         {
             //return err.getMessage(); 
             return 'Error => '+ err.getMessage();
         }

     }
     
     //For Validation of the Payment Plan For Invoice Method...
     Webservice static string canPaymentPlanImplementMethpd(ID objectID , string licenseType)
     {
        Map<string,string> locationTypeMap = new Map<string,string>();
        
        try
        {
            //First Getting all the location type...
            if(objectID != null && licenseType == 'Tenancy')
            {
                for(Tenancy_Contract__c tenancyObject : [select id,Tenant__c,Account_Activity__c,Account_Expiry_Date__c,Location_type__c, Tenancy_Contract_Cancellation_Date__c FROM Tenancy_Contract__c where Tenancy_Contract_Cancellation_Date__c =: null AND Id =: objectID ])  
                {
                    locationTypeMap.put(tenancyObject.Location_type__c,tenancyObject.Location_type__c);
                    
                    //Adding in the list...
                    //tenacnyObjectList.add(tenancyObject);
                }
            }
            else if (objectID != null && licenseType == 'Amendment')
            {
            
                for(Amendment__c amendmentObject : [select Account__c,Account_Legal_Status__c,Record_Type_Name__c,New_Location_Type_1__c,New_Location_Type_2__c,New_Location_Type_3__c,Account_License__c,New_License_Type__c,Total_Share_Holders__c,NTCDI__c,OTCDL__c,Company_Capital__c,New_Location_1_Name__c,New_Location_2_Name__c,New_Location_3_Name__c,New_Location__c,New_Location_2__c,New_Location_3__c,NLPPD_3__c,NLPPD_2__c,NLPPD__c,PTCPPD__c,Id,Keys_Required__c,Amendment_Application_Status__c from Amendment__c where Id =:objectID])
                {
                    if(amendmentObject.New_Location_Type_1__c != null)
                        locationTypeMap.put(amendmentObject.New_Location_Type_1__c,amendmentObject.New_Location_Type_1__c); 
                    if(amendmentObject.New_Location_Type_2__c != null)
                        locationTypeMap.put(amendmentObject.New_Location_Type_2__c,amendmentObject.New_Location_Type_2__c);
                    if(amendmentObject.New_Location_Type_3__c != null)
                        locationTypeMap.put(amendmentObject.New_Location_Type_3__c,amendmentObject.New_Location_Type_3__c); 
                                            
                    //Adding in the List...                     
                    //amendmentObjectList.add(amendmentObject);
                    
                }
                
            }
            else if(objectID != null && licenseType == 'New License')
            {
                for(Location_Booking_Information__c locationObject : [Select Location__r.Name,Location__r.Location_Type__c,Location__r.Rental_Rate__c,Location__r.Fee__r.Name, Location__r.Fee__r.Fee_Type__c, Location__r.Id, Location__c, License_Booking_Status__c, Id, Booking_Released_Date__c, Booking_Leasing_Issue_Date__c, Booking_Date__c, Account__c From Location_Booking_Information__c where Account__c =: objectID AND License_Booking_Status__c = 'Booked'])    
                {
                    locationTypeMap.put(locationObject.Location__r.Location_Type__c,locationObject.Location__r.Location_Type__c);
                }
            }   
            
            else if(objectID != null && licenseType == 'Renewal')
            {
                for(Tenancy_Contract__c tenancyObject : [select id,Location_type__c, Tenancy_Contract_Cancellation_Date__c FROM Tenancy_Contract__c where Tenancy_Contract_Cancellation_Date__c =: null AND Tenant__c =: objectID]) 
                {
                    locationTypeMap.put(tenancyObject.Location_type__c,tenancyObject.Location_type__c);
                }   
            
            }
            
            else if(objectID != null && (licenseType == 'Renewal Amendment'))
            {
                for(Account_Location__c accountLocationObject : [Select New_Location__r.Rental_Rate__c,New_Location__r.Location_Type__c,Account_Expiry_Date__c,renewAddLocationFlag__c,Previous_Tenancy_Contract__r.Location__r.Location_Type__c,Previous_Tenancy_Contract__r.Account_Today_Expiry_Date__c,Previous_Tenancy_Contract__r.Location__r.Rental_Rate__c,Previous_Tenancy_Contract__r.Account_Expiry_Date__c,isRenewed__c, Previous_Tenancy_Contract__r.Fine_Per_Day__c, Previous_Tenancy_Contract__r.Tenancy_Contract_Cancellation_Date__c, Previous_Tenancy_Contract__r.Location_type__c, Previous_Tenancy_Contract__r.Rental_Rate__c, Previous_Tenancy_Contract__r.Tenancy_Contract_Expiry_Date__c, Previous_Tenancy_Contract__r.Tenancy_Contract_Start_Date__c, Previous_Tenancy_Contract__r.Tenant__c, Previous_Tenancy_Contract__r.Location__c, Previous_Tenancy_Contract__r.Location__r.Current_Tenancy_Contract__c, Previous_Tenancy_Contract__r.Id, Previous_Tenancy_Contract__c, Previous_Location__c, New_Location__c, Name, Id, Flag__c, Edit_Flag__c, Delete_Flag__c, Add_Flag__c, Account__c From Account_Location__c where Account__c =: objectID AND Delete_Flag__c =: false AND isRenewed__c =: false])  
                {
                    if(accountLocationObject.renewAddLocationFlag__c != true && accountLocationObject.New_Location__c != null)
                        locationTypeMap.put(accountLocationObject.New_Location__r.Location_Type__c,accountLocationObject.New_Location__r.Location_Type__c);
                    else if(accountLocationObject.Previous_Tenancy_Contract__r.Location__r.Current_Tenancy_Contract__c != null && accountLocationObject.Previous_Tenancy_Contract__c == accountLocationObject.Previous_Tenancy_Contract__r.Location__r.Current_Tenancy_Contract__c)
                        locationTypeMap.put(accountLocationObject.Previous_Tenancy_Contract__r.Location__r.Location_Type__c,accountLocationObject.Previous_Tenancy_Contract__r.Location__r.Location_Type__c);
                
                }
            }   
            
            //Location Type Map...
            if(locationTypeMap.size() > 0)
            {
                
                List<Payment_Plan__c> paymentPlanList = new List<Payment_Plan__c>([Select isActive__c, Percent__c, Location_Type__c, Installment__c, Id, Action__c From Payment_Plan__c WHERE isActive__c =: true AND License_Application_Type__c =: licenseType  AND Location_Type__c IN : locationTypeMap.KeySet()]);
                
                if(paymentPlanList.size() > 0)
                    return 'Sucess';
                else 
                    return 'There is no Payment Plan';
                
                
                    
            }
            
            //Return the values...
            return 'There is no Payment Plan';
            
        }
        catch(System.Exception err)
        {
             //return err.getMessage(); 
             System.debug('The Error is : '+ err.getMessage());
             return err.getMessage();
        }
            
        
     
     }
     
     
     //For Validation of Amendment Process  Button....
     Webservice static string validateForAccountLicensePDFButton(ID accountId)
     {
         try
         {
             List<Tenancy_Contract__c> tenancyObjectList = new List<Tenancy_Contract__c>([select Id,Tenancy_Contract_Cancellation_Date__c,Tenant__c FROM Tenancy_Contract__c where Tenancy_Contract_Cancellation_Date__c =: null AND Tenant__c =: accountId]);
             
             if(tenancyObjectList.size() > 0)
                return 'Success';
             else
                return 'Error';
             
         }
         catch(System.Exception err)
         {
             //return err.getMessage(); 
             return 'Error';
         }
     
     }
     //For Validation of Amendment Process  Button....
     Webservice static string validateForAmendment(ID accountId)
     {
         try
         {
             /*List<Account> accountObjectList = new List<Account>([Select Id,License_Expiry_Date__c from Account where Id =: accountId AND License_Expiry_Date__c >: System.Today()]);
             if(accountObjectList.size() == 0)
             {
                 return 'Account';
             
             }
             else
             {
                 List<Fines__c> finesObjectList = new List<Fines__c>([select id,Account__c,Status__c from Fines__c where Status__c = 'Suspended' AND Account__c =: accountId]);
             
                 if(finesObjectList.size() > 0)
                 {
                     return 'Suspension';
                 
                 }
                 else
                 {
                     List<Tenancy_Contract__c> tenancyContractList = new List<Tenancy_Contract__c>([select Id,Tenancy_Contract_Cancellation_Date__c,Tenant__c,Tenancy_Contract_Expiry_Date__c from Tenancy_Contract__c where Tenancy_Contract_Expiry_Date__c >: System.today() AND Tenant__c =: accountId AND Tenancy_Contract_Cancellation_Date__c = null]);
                     
                     if(tenancyContractList.size() == 0)    
                     {
                         return 'Tenancy';
                     }
                 
                 
                 }
             
             }*/
             
             List<Fines__c> finesObjectList = new List<Fines__c>([select id,Account__c,Status__c from Fines__c where Status__c = 'Suspended' AND Account__c =: accountId]);
             
             if(finesObjectList.size() > 0)
             {
                 return 'Suspension';
             
             }
             
             
             return 'Success';
         }
         catch(System.Exception err)
         {
             //return err.getMessage(); 
             return 'Error';
         }
     
     }
     //For Submit for Manager Approval Button....
     WebService static string submitForManagerApproval(ID accountId)
     {
          try
          {   
              System.debug('The Current Login User Id => '+ USERINFO.getUserName() + ' && THe Current Login User Profile => '+USERINFO.getProfileId());
              //Now Calling the Approval process to be initiate...
              Approval.ProcessSubmitRequest approvalRequest = new Approval.ProcessSubmitRequest();
                
              approvalRequest.setComments('Submit For Manager Approval');
              approvalRequest.setObjectId(accountId);
              
              // submit the approval request for processing
              if(!Test.isRunningTest())
              {
                  Approval.ProcessResult approvalResult = Approval.process(approvalRequest);
                                
                  if(approvalResult.isSuccess())
                    return 'Success';
                  else
                    return null;
              }
              else
              {
                 return null;
              }
                  
          }
          catch(System.Exception err)
          {
            //return err.getMessage(); 
            return 'The Approval Process is not matching any criteria !!!';
          }
     
         
     }
     
     
      //For Submit for Back Office Approval Button....
     WebService static string submitForBackofficeApproval(ID accountId)
     {
          try
          {   
              System.debug('The Current Login User Id => '+ USERINFO.getUserName() + ' && The Current Login User Profile => '+USERINFO.getProfileId());
              //Now Calling the Approval process to be initiate...
              Approval.ProcessSubmitRequest approvalRequest = new Approval.ProcessSubmitRequest();
                
              approvalRequest.setComments('Submit For Back Office Approval');
              approvalRequest.setObjectId(accountId);
              
              // submit the approval request for processing
              if(!Test.isRunningTest())
              {
                  Approval.ProcessResult approvalResult = Approval.process(approvalRequest);
                                
                  if(approvalResult.isSuccess())
                    return 'Success';
                  else
                    return null;
              }
              else
              {
                 return null;
              }
                  
          }
          catch(System.Exception err)
          {
            //return err.getMessage(); 
            return 'The Approval Process is not matching any criteria !!!';
          }
     
         
     }
     
     
    
     //For Amendment License Issued Button Method....
     WebService static string amendmenLicenseIssuedMethod(ID amendmentId)
     {
        try
        {
            Amendment__c amendmentObject = new Amendment__c();
            
            amendmentObject = [Select Amendment_Application_Status__c,Send_Newspaper_Notification_Flag__c, Id From Amendment__c where Id =:amendmentId];
            
            if(amendmentObject != null)
            {
                
                amendmentObject.Amendment_Application_Status__c = 'License Issued';
                update amendmentObject;
                
                //return the Sucess... 
                return 'Success';
            }
            
            
            //Return the Null;
            return 'Amendment Id is Not Valid';
        }
        catch(System.Exception err)
        {
            System.debug(err.getMessage()); 
            return err.getMessage();
        }
        
     }
     
     //For Amendment Performa Invoice Issued Button Method....
     WebService static string amendmenPerformaInvoiceMethod(ID amendmentId)
     {
        try
        {
            Amendment__c amendmentObject = new Amendment__c();
            
            amendmentObject = [Select Amendment_Application_Status__c,Send_Newspaper_Notification_Flag__c, Id From Amendment__c where Id =:amendmentId];
            
            if(amendmentObject != null)
            {
                
                amendmentObject.Amendment_Application_Status__c = 'Performa Invoice Issued';
                update amendmentObject;
                
                //return the Sucess... 
                return 'Success';
            }
            
            
            //Return the Null;
            return 'Amendment Id is Not Valid';
        }
        catch(System.Exception err)
        {
            System.debug(err.getMessage()); 
            return err.getMessage();
        }
        
     }  
     //For Amendment Send Notification Email License Button Method....
     WebService static string amendmentEmailNotificationLicenseMethod(ID amendmentId)
     {
        try
        {
            Amendment__c amendmentObject = new Amendment__c();
            
            amendmentObject = [Select Amendment_Application_Status__c,Send_Newspaper_Notification_Flag__c, Id From Amendment__c where Id =:amendmentId  AND Send_Newspaper_Notification_Flag__c =: false];
            
            if(amendmentObject != null)
            {
                amendmentObject.Send_Newspaper_Notification_Flag__c = true;
                amendmentObject.Amendment_Application_Status__c = 'Newspaper Notification Sent';
                update amendmentObject;
                
                //return the Sucess... 
                return 'Success';
            }
            
            
            //Return the Null;
            return 'Amendment Id is Not Valid';
        }
        catch(System.Exception err)
        {
            System.debug(err.getMessage()); 
            return err.getMessage();
        }
        
     }
     
     //For Cancel Email Notification License Button Method....
     WebService static string cancelEmailNotificationLicenseMethod(ID accountId)
     {
        try
        {
            Account accountObject = new Account();
            
            accountObject = [Select License_Application_Step__c,Send_Newspaper_Notification_Flag__c, Id From Account where Id =: accountId AND Send_Newspaper_Notification_Flag__c = false ];
            
            if(accountObject != null)
            {
                accountObject.Send_Newspaper_Notification_Flag__c =true;
                accountObject.License_Application_Step__c = 'Newspaper Notification Sent';
                update accountObject;
                
                //return the Sucess... 
                return 'Success';
            }
            
            
            //Return the Null;
            return 'Account Id is Not Valid';
        }
        catch(System.Exception err)
        {
            System.debug(err.getMessage()); 
            return err.getMessage();
        }
        
     }
     
     //For Drop Location Button Method....
     WebService static string dropLocationMethod(ID locationId)
     {
        try
        {
            Location__c locationObject = new Location__c();
            
            locationObject = [Select underCancellationFlag__c,Current_Tenancy_Contract__c,underVacantLocationFlag__c,Location_Booked_Information_Flag__c, Id From Location__c where Id =: locationId];
            
            if(locationObject != null)
            {
                locationObject.Location_Booked_Information_Flag__c = false;
                locationObject.Current_Tenancy_Contract__c = null;
                locationObject.underVacantLocationFlag__c = false;
                locationObject.underCancellationFlag__c =  false;
                
                
                update locationObject;
                
                //return the Sucess... 
                return 'Success';
            }
            
            
            //Return the Null;
            return 'Location Id is Not Valid';
        }
        catch(System.Exception err)
        {
            System.debug(err.getMessage()); 
            return err.getMessage();
        }
        
     }
     
     //For Un Drop Location Button Method....
     WebService static string unDropLocationMethod(ID locationId)
     {
        try
        {
            Location__c locationObject = new Location__c();
            
            locationObject = [Select underCancellationFlag__c,Current_Tenancy_Contract__c,underVacantLocationFlag__c,Location_Booked_Information_Flag__c, Id From Location__c where Id =: locationId];
            
            if(locationObject != null)
            {
                locationObject.underVacantLocationFlag__c = false;
                
                update locationObject;
                
                //return the Sucess... 
                return 'Success';
            }
            
            
            //Return the Null;
            return 'Location Id is Not Valid';
        }
        catch(System.Exception err)
        {
            System.debug(err.getMessage()); 
            return err.getMessage();
        }
        
     }
     
     //For Under Vacant Location Button Method....
     WebService static string underVacantLocationMethod(ID locationId)
     {
        try
        {
            Location__c locationObject = new Location__c();
            
            locationObject = [Select underCancellationFlag__c,Current_Tenancy_Contract__c,underVacantLocationFlag__c,Location_Booked_Information_Flag__c, Id From Location__c where Id =: locationId];
            
            if(locationObject != null)
            {
                locationObject.underVacantLocationFlag__c = true;
                
                update locationObject;
                
                //return the Sucess... 
                return 'Success';
            }
            
            
            //Return the Null;
            return 'Location Id is Not Valid';
        }
        catch(System.Exception err)
        {
            System.debug(err.getMessage()); 
            return err.getMessage();
        }
        
     }
     
     //For Visa Values Button Method....
     WebService static string visaValuesCalculationsMethod(ID accountID)
     {
        try
        {
            List<Account> accountUpdationList = new List<Account>();
    
            //Store the Account and Account ids in a List...
            List<Account> accountObjectList = new List<Account>([select id,Total_Number_of_Absconding_Visa__c,Cancel_Residence_Without_Doc_visa_quota__c,Total_Number_of_Expired_Passport__c,Total_Number_of_Passport_Outside__c,Cancelled_Residence_visa_quota__c,Visit_Visa_Quota__c,Expired_Residence_visa_quota__c,Residence_Visa_Quota_Available__c from Account where id =: accountID]);
            
            //We query because of the Old Trigger Values and the New Trigger Values...
            List<Contact> contactObjectList = new List<Contact>([select id,Account.Id,Current_Employer__c,Legacy_Visa_Type__c,Visa_Validity_Status__c,Visa_Package__c,Passport_Status__c,Passport_Movement_Status__c from Contact where Current_Employer__c =: accountID]);
            
            //Now Traverse the Account Object Maps...
            for(Account accountObject : accountObjectList)
            {
                //Fist Reset all the values...
                accountObject.Residence_Visa_Quota_Used__c = 0;
                accountObject.Visit_Visa_Quota__c = 0;
                accountObject.Expired_Residence_visa_quota__c = 0;
                accountObject.Cancelled_Residence_visa_quota__c = 0;
                
                accountObject.Total_Number_of_Absconding_Visa__c = 0;
                accountObject.Cancel_Residence_Without_Doc_visa_quota__c = 0;
                accountObject.Total_Number_of_Expired_Passport__c = 0;
                accountObject.Total_Number_of_Passport_Outside__c = 0;
                    
                //Iterate through all Contacts to get the childs of the currrent Account and add the corresponding fields of child together to form a roll up summary filed in the parent Account   
                for(Contact contactObject :  contactObjectList)
                {
                    //For Visit Visa Used....
                    if((contactObject.Current_Employer__c == accountObject.id) && (contactObject.Visa_Package__c == 'Visit Visa'))      
                    {
                        accountObject.Visit_Visa_Quota__c += 1;         
                    }
                    //For Cancelled Residence Visa Quota Used...
                    else if((contactObject.Current_Employer__c == accountObject.id) && (contactObject.Visa_Package__c == 'Employment' || contactObject.Visa_Package__c == 'Transfer') && (contactObject.Visa_Validity_Status__c == 'Cancelled') && (contactObject.Legacy_Visa_Type__c != 'Entry Permit'))
                    {
                        accountObject.Cancelled_Residence_visa_quota__c += 1;
                    }
                    
                    //For Expired Residence Visa Quota Used...
                    else if((contactObject.Current_Employer__c == accountObject.id) && (contactObject.Visa_Package__c == 'Employment' || contactObject.Visa_Package__c == 'Transfer') && (contactObject.Visa_Validity_Status__c == 'Expired') && (contactObject.Legacy_Visa_Type__c != 'Entry Permit'))
                    {
                        accountObject.Expired_Residence_visa_quota__c += 1;
                        //Change Request to Count expired visa in Visa Quota Used...
                        accountObject.Residence_Visa_Quota_Used__c += 1;
                    }
                    //For Residence Visa Quota Used...
                    else if((contactObject.Current_Employer__c == accountObject.id) && (contactObject.Visa_Package__c == 'Employment' || contactObject.Visa_Package__c == 'Transfer') && (contactObject.Visa_Validity_Status__c != 'Cancelled' && contactObject.Visa_Validity_Status__c != 'Unavailable' && contactObject.Visa_Validity_Status__c != 'Absconding' && contactObject.Visa_Validity_Status__c != 'Cancelled with Absconding'))
                    {
                        accountObject.Residence_Visa_Quota_Used__c += 1;
                    }
                    
                    //For Absconding... (Work FIne till 21/10/2012) For the New change Request...
                    /*else if((contactObject.Current_Employer__c == accountObject.id) && (contactObject.Legacy_Visa_Type__c == 'Absconding' || contactObject.Visa_Validity_Status__c == 'Absconding' || contactObject.Visa_Validity_Status__c == 'Cancelled with Absconding'))      
                    {
                        accountObject.Total_Number_of_Absconding_Visa__c += 1;         
                    }*/
                    else if((contactObject.Current_Employer__c == accountObject.id) && (contactObject.Legacy_Visa_Type__c == 'Absconding' || contactObject.Visa_Validity_Status__c == 'Absconding'))      
                    {
                        accountObject.Total_Number_of_Absconding_Visa__c += 1;         
                    }
                    else if((contactObject.Current_Employer__c == accountObject.id) && (contactObject.Visa_Validity_Status__c == 'Cancelled with Absconding'))      
                    {
                        accountObject.Cancelled_Residence_visa_quota__c += 1;       
                    }
                     
                    //For Cancelled Without Document Quota Used...
                    if((contactObject.Current_Employer__c == accountObject.id) && (contactObject.Visa_Package__c == 'Employment' || contactObject.Visa_Package__c == 'Transfer') && (contactObject.Visa_Validity_Status__c == 'Cancellation Without Exist') && (contactObject.Legacy_Visa_Type__c != 'Entry Permit'))
                    {
                        accountObject.Cancel_Residence_Without_Doc_visa_quota__c += 1;
                    }
                    
                    //*************************** For passport Information ********************
                    if((contactObject.Current_Employer__c == accountObject.id) && (contactObject.Passport_Status__c == 'Expired'))      
                    {
                        accountObject.Total_Number_of_Expired_Passport__c += 1;         
                    }
                    
                    //For Passport Movement Status...
                    if((contactObject.Current_Employer__c == accountObject.id) && (contactObject.Passport_Movement_Status__c == 'Out'))
                    {
                        accountObject.Total_Number_of_Passport_Outside__c += 1;
                    }
                    
                }
                
                
                
                
                
                System.debug('The Residence Visa Quota => ' + accountObject.Residence_Visa_Quota_Used__c );
                System.debug('The Expired Residence Visa Quota => '+accountObject.Expired_Residence_visa_quota__c );
                System.debug('The Cancelled Visa Quota => '+ accountObject.Cancelled_Residence_visa_quota__c);
                System.debug('The Visit Visa Quota => '+accountObject.Visit_Visa_Quota__c );
                //Adding the Account in Account Update List...
                accountUpdationList.add(accountObject);  
                
            }
            
            
            
            //Update the Accounts... 
            if(accountUpdationList.size() > 0)
                update(accountUpdationList);
            
        
            //Return the Null;
            return 'Success';
        }
        catch(System.Exception err)
        {
            System.debug(err.getMessage()); 
            return err.getMessage();
        }
        
     }
     
     //For Cancel License Button Method....
     WebService static string cancelLicenseMethod(ID accountId)
     {
        try
        {
            Account accountObject = new Account();
            RecordType recordType = new RecordType();
            
            //recordType = [select Id,SObjectType,IsActive,DeveloperName from RecordType where SObjectType =: 'Account' and IsActive =: true and DeveloperName =: 'Cancelled'];
            recordType = [select Id,SObjectType,IsActive,DeveloperName from RecordType where SObjectType =: 'Account' and IsActive =: true and DeveloperName =: 'Cancellation_Front_Office'];
            accountObject = [select Id,OwnerId,Login_User_Id__c,Record_Approver_Id__c, RecordTypeId,License_Application_Type__c,License_Application_Step__c,Cancellation_Start_Date__c from Account where Id=: accountId];
            
            
            //Just Update the Record....
            accountObject.License_Application_Step__c = 'Cancellation Started';
            accountObject.License_Application_Type__c = 'Cancellation';
            //accountObject.Cancellation_Start_Date__c = System.Today();
            accountObject.RecordTypeId = recordType.Id;
            accountObject.Record_Approver_Id__c = accountObject.Login_User_Id__c;
            accountObject.OwnerId = accountObject.Login_User_Id__c;
            update accountObject;
            
            List<SLA__c> slaList = new List<SLA__c>();
            
            integer slaHours = 0;
            boolean slaFlag = false;
            
            for(SLA_Custom_Setting__c slaRecord : SLA_Custom_Setting__c.getAll().values())
            {
                if(slaRecord.Application_Type__c == 'Cancellation' && slaRecord.Process_Type__c == 'License')
                {
                    slaHours = integer.valueof(slaRecord.SLA_Hours__c);
                    slaFlag  = true;
                    break;
                }
                                        
            }
            
            if(slaFlag)
            {
                // Assumes the BSC work hours are the default for the Org
                List<BusinessHours> businessHoursObjectList = new List<BusinessHours>([select id from businesshours where isDefault = true LIMIT 1]) ;
    
                if(businessHoursObjectList.size() > 0)
                {
                    SLA__c slaObject = new SLA__c();
                    slaObject.SLA_Hours__c = slaHours ;
                    slaObject.Actual_Start_Date_Time__c = DateTime.Now();
                    // BSC works 11.5 hours / day (8:00 AM - 7:30 PM, M-F). Our SLA is 2-days (23 business hours)
                    System.debug('The Actual Start Time => '+ slaObject.Actual_Start_Date_Time__c );
                    System.debug('The Expected End Date => '+ slaObject.Actual_Start_Date_Time__c.addhours(slaHours));
                    System.debug('The Business Hour Date => ' + BusinessHours.add(businessHoursObjectList[0].id, slaObject.Actual_Start_Date_Time__c, slaHours * 60 * 60 * 1000L));
                    System.debug('The Business Hour Date GMT => ' + BusinessHours.addGmt(businessHoursObjectList[0].id, slaObject.Actual_Start_Date_Time__c, slaHours * 60 * 60 * 1000L));
                    slaObject.Expected_End_Date__c = BusinessHours.addGmt(businessHoursObjectList[0].id, slaObject.Actual_Start_Date_Time__c, slaHours * 60 * 60 * 1000L); 
                    //slaObject.Expected_End_Date__c = DateTime.Now().addhours(slaHours);
                    slaObject.License__c = accountObject.Id;
                    slaObject.Application_Type__c = 'Cancellation';
                    slaObject.Process_Type__c = 'License';
                    upsert slaObject;
                    
                }
            }        
            
            //Now Return the values...
            return 'Success';
            
        }
        catch(System.Exception err)
        {
            //return err.getMessage(); 
            return 'The Approval Process is not matching any criteria !!!';
        }
     }  
    
    WebService static String serviceLetterGenerateLetterButton(ID serviceLetterID)
    {
        try
        {
            List<Request__c> serviceLetterObjectList  = new List<Request__c>([select Request_Status__c, RecordTypeId,Record_Type_Name__c from Request__c where id =: serviceLetterID]);
            // Check from the value of the record type to update
            Map<string,ID> recordTypeNameMap = new Map<string,ID>();
           
            if (serviceLetterObjectList.size() > 0)
            {
                for(Request__c serviceObject : serviceLetterObjectList )
                {
                    serviceObject.Request_Status__c = 'Ready for Signature';
                
                }
            
                update serviceLetterObjectList;
            }
            
            return 'Success';
        }        
        catch(System.Exception err)
        {
            return err.getMessage();
        }        
    }
    
    // OMM-20131125
    // For Update the record type in the Service Letter
    WebService static String serviceLetterApproveButton(ID serviceLetterID)
    {
        try
        {
                List<Request__c> serviceLetterObjectList  = new List<Request__c>([select RecordTypeId,Record_Type_Name__c,Request_Status__c  from Request__c where id =: serviceLetterID]);
                // Check from the value of the record type to update
                Map<string,ID> recordTypeNameMap = new Map<string,ID>();
               
                if (serviceLetterObjectList.size() > 0)
                {
                    for(RecordType recordTypeObject : [select id,DeveloperName from RecordType where sObjectType= 'Request__c' AND IsActive = true])
                    {
                        recordTypeNameMap.put(recordTypeObject.DeveloperName, recordTypeObject.id);
                    }
                    /*
                    if (serviceLetterObjectList[0].Record_Type_Name__c == 'Amendment')
                    {
                        if(recordTypeNameMap.get('Amendment_Approved') != null)
                            serviceLetterObjectList[0].RecordTypeId = recordTypeNameMap.get('Amendment_Approved') ;
                    }
                    else if (serviceLetterObjectList[0].Record_Type_Name__c == 'Bank_Letter')
                    {
                        if(recordTypeNameMap.get('Bank_Letter_Approved') != null)
                            serviceLetterObjectList[0].RecordTypeId = recordTypeNameMap.get('Bank_Letter_Approved') ;
                    }
                    else if (serviceLetterObjectList[0].Record_Type_Name__c == 'Certificate')
                    {
                       if(recordTypeNameMap.get('Certificate_Approved') != null)
                            serviceLetterObjectList[0].RecordTypeId = recordTypeNameMap.get('Certificate_Approved') ;
                    }
                    else if (serviceLetterObjectList[0].Record_Type_Name__c == 'Driving_License')
                    {
                       if(recordTypeNameMap.get('Driving_License_Approved') != null)
                            serviceLetterObjectList[0].RecordTypeId = recordTypeNameMap.get('Driving_License_Approved') ;
                    }
                    else if (serviceLetterObjectList[0].Record_Type_Name__c == 'Entry_Permit')
                    {
                        if(recordTypeNameMap.get('Entry_Permit_Approved') != null)
                            serviceLetterObjectList[0].RecordTypeId = recordTypeNameMap.get('Entry_Permit_Approved') ;
                    }
                    else if (serviceLetterObjectList[0].Record_Type_Name__c == 'Lost_Document')
                    {
                         if(recordTypeNameMap.get('Lost_Document_Approved') != null)
                            serviceLetterObjectList[0].RecordTypeId = recordTypeNameMap.get('Lost_Document_Approved') ;
                    }
                    else if (serviceLetterObjectList[0].Record_Type_Name__c == 'Ministry_of_Economy')
                    {
                        if(recordTypeNameMap.get('Ministry_of_Economy_Approved') != null)
                            serviceLetterObjectList[0].RecordTypeId = recordTypeNameMap.get('Ministry_of_Economy_Approved') ;
                    }
                    else if (serviceLetterObjectList[0].Record_Type_Name__c == 'No_Objection_Letter')
                    {
                         if(recordTypeNameMap.get('No_Objection_Letter_Approved') != null)
                            serviceLetterObjectList[0].RecordTypeId = recordTypeNameMap.get('No_Objection_Letter_Approved') ;
                    }
                    else if (serviceLetterObjectList[0].Record_Type_Name__c == 'Sewage')
                    {
                       if(recordTypeNameMap.get('Sewage_Approved') != null)
                            serviceLetterObjectList[0].RecordTypeId = recordTypeNameMap.get('Sewage_Approved') ;
                    }
                    else if (serviceLetterObjectList[0].Record_Type_Name__c == 'Telephone_Line')
                    {
                        if(recordTypeNameMap.get('Telephone_Line_Approved') != null)
                            serviceLetterObjectList[0].RecordTypeId = recordTypeNameMap.get('Telephone_Line_Approved') ;
                    }
                    else if (serviceLetterObjectList[0].Record_Type_Name__c == 'Vehicle')
                    {
                        if(recordTypeNameMap.get('Vehicle_Approved') != null)
                            serviceLetterObjectList[0].RecordTypeId = recordTypeNameMap.get('Vehicle_Approved') ;
                    }
                    */
                    //PO change 03252014
                    //PO remove 08/14/2014 does not seem to be true - record types names are all different
                    /*
                    if (serviceLetterObjectList[0].Record_Type_Name__c == 'Request_Service_Letter_Amendment')
                    {
                        if(recordTypeNameMap.get('Request_Service_Letter_Amendment_Approved') != null)
                            serviceLetterObjectList[0].RecordTypeId = recordTypeNameMap.get('Request_Service_Letter_Amendment_Approved') ;
                    }
                    else if (serviceLetterObjectList[0].Record_Type_Name__c == 'Request_Service_Letter_Bank_Letter')
                    {
                        if(recordTypeNameMap.get('Request_Service_Letter_Bank_Letter_Approved') != null)
                            serviceLetterObjectList[0].RecordTypeId = recordTypeNameMap.get('Request_Service_Letter_Bank_Letter_Approved') ;
                    }
                    else if (serviceLetterObjectList[0].Record_Type_Name__c == 'Request_Service_Letter_Certificate')
                    {
                       if(recordTypeNameMap.get('Request_Service_Letter_Certificate_Approved') != null)
                            serviceLetterObjectList[0].RecordTypeId = recordTypeNameMap.get('Request_Service_Letter_Certificate_Approved') ;
                    }
                    else if (serviceLetterObjectList[0].Record_Type_Name__c == 'Request_Service_Letter_Driving_License')
                    {
                       if(recordTypeNameMap.get('Request_Service_Letter_Driving_License_Approved') != null)
                            serviceLetterObjectList[0].RecordTypeId = recordTypeNameMap.get('Request_Service_Letter_Driving_License_Approved') ;
                    }
                    else if (serviceLetterObjectList[0].Record_Type_Name__c == 'Request_Service_Letter_Entry_Permit')
                    {
                        if(recordTypeNameMap.get('Request_Service_Letter_Entry_Permit_Approved') != null)
                            serviceLetterObjectList[0].RecordTypeId = recordTypeNameMap.get('Request_Service_Letter_Entry_Permit_Approved') ;
                    }
                    else if (serviceLetterObjectList[0].Record_Type_Name__c == 'Request_Service_Letter_Lost_Document')
                    {
                         if(recordTypeNameMap.get('Request_Service_Letter_Lost_Document_Approved') != null)
                            serviceLetterObjectList[0].RecordTypeId = recordTypeNameMap.get('Request_Service_Letter_Lost_Document_Approved') ;
                    }
                    else if (serviceLetterObjectList[0].Record_Type_Name__c == 'Request_Service_Letter_Ministry_of_Economy')
                    {
                        if(recordTypeNameMap.get('Request_Service_Letter_Ministry_of_Economy_Approved') != null)
                            serviceLetterObjectList[0].RecordTypeId = recordTypeNameMap.get('Request_Service_Letter_Ministry_of_Economy_Approved') ;
                    }
                    else if (serviceLetterObjectList[0].Record_Type_Name__c == 'Request_Service_Letter_No_Objection_Letter')
                    {
                         if(recordTypeNameMap.get('Request_Service_Letter_No_Objection_Letter_Approved') != null)
                            serviceLetterObjectList[0].RecordTypeId = recordTypeNameMap.get('Request_Service_Letter_No_Objection_Letter_Approved') ;
                    }
                    else if (serviceLetterObjectList[0].Record_Type_Name__c == 'Request_Service_Letter_Sewage')
                    {
                       if(recordTypeNameMap.get('Request_Service_Letter_Sewage_Approved') != null)
                            serviceLetterObjectList[0].RecordTypeId = recordTypeNameMap.get('Request_Service_Letter_Sewage_Approved') ;
                    }
                    else if (serviceLetterObjectList[0].Record_Type_Name__c == 'Request_Service_Letter_Telephone_Line')
                    {
                        if(recordTypeNameMap.get('Request_Service_Letter_Telephone_Line_Approved') != null)
                            serviceLetterObjectList[0].RecordTypeId = recordTypeNameMap.get('Request_Service_Letter_Telephone_Line_Approved') ;
                    }
                    else if (serviceLetterObjectList[0].Record_Type_Name__c == 'Request_Service_Letter_Vehicle')
                    {
                        if(recordTypeNameMap.get('Request_Service_Letter_Vehicle_Approved') != null)
                            serviceLetterObjectList[0].RecordTypeId = recordTypeNameMap.get('Request_Service_Letter_Vehicle_Approved') ;
                    }
                    */                   
                     //PO change 03252014
                    if ( serviceLetterObjectList[0].Request_Status__c != 'Approved')
                        serviceLetterObjectList[0].Request_Status__c = 'Approved';
                        
                     serviceLetterObjectList[0].OwnerId = UserInfo.getUserId(); 
                    
                    if (serviceLetterObjectList.size() > 0)
                    {
                        update  serviceLetterObjectList;
                    } 
                }
                
                return 'Success';
        }
        
        catch(System.Exception err)
        {
            return err.getMessage(); 
        }
    }    
    
    // For Rejection Service Letter, update status , send letter and cancel SLA
    WebService static String serviceLetterRejectButton(ID serviceLetterID)
    {
        try
        {
            String Result = '';
            List<Request__c> serviceLetterObject = new List<Request__c>([select Request_Status__c from Request__c where id =: serviceLetterID]);
            // Check from the value of the record type to update
            
            if (serviceLetterObject.size() > 0)
            {
                serviceLetterObject[0].Request_Status__c ='Rejected';
                //if ( serviceLetterObject[0].Rejection_Reason__c != null ){
                    update serviceLetterObject;
                    Result  = 'Success';
                //}
                //else{
                  //  Result  = 'Rejection Reason is Required';
                //} 
            }
            return Result ;
            
        }
        catch(System.Exception err)
        {
            return err.getMessage();
        }        
    }
    
    
    // For Cancel Service Letter, update status
    WebService static String serviceLetterCancelButton(ID serviceLetterID)
    {
        try
        {
            List<Request__c> serviceLetterObject = new List<Request__c>([select Request_Status__c from Request__c where id =: serviceLetterID]);
            // Check from the value of the record type to update
            
            if (serviceLetterObject.size() > 0)
            {
                serviceLetterObject[0].Request_Status__c ='Cancelled';
                update serviceLetterObject; 
            }
            return 'Success';
            
        }
        catch(System.Exception err)
        {
            return err.getMessage();
        }        
    }
    
    // For Cancel Service Letter, update status
    WebService static String serviceLetterDeliveredButton(ID serviceLetterID)
    {
        try
        {
            List<Request__c> serviceLetterObject = new List<Request__c>([select Request_Status__c from Request__c where id =: serviceLetterID]);
            // Check from the value of the record type to update
            if (serviceLetterObject.size() > 0)
            {
                    serviceLetterObject[0].Request_Status__c ='Delivered';
                    update serviceLetterObject;
            }
            return 'Success';
        }
        catch(System.Exception err)
        {
            return err.getMessage();
        }        
    }
    
    
    // serviceLetterConfirmManualDeliveryButton
    WebService static String serviceLetterConfirmManualDeliveryButton(ID serviceLetterID)
    {
        try
        {
            List<Request__c> serviceLetterObject = new List<Request__c>([select Request_Status__c from Request__c where id =: serviceLetterID]);
            // Check from the value of the record type to update
            if (serviceLetterObject.size() > 0)
            {
                    //serviceLetterObject[0].Request_Status__c ='Delivered';
                    serviceLetterObject[0].Request_Status__c ='Out for Delivery';
                    update serviceLetterObject;
            }
            return 'Success';
        }
        catch(System.Exception err)
        {
            return err.getMessage();
        }        
    }
    
    
    // serviceLetterConfirmManualDeliveryButton
    WebService static String serviceLetterConfirmDeliveryByDeliveryDepartmentButton(ID serviceLetterID)
    {
        try
        {
            List<Request__c> serviceLetterObject = new List<Request__c>([select Request_Status__c from Request__c where id =: serviceLetterID]);
            // Check from the value of the record type to update
            if (serviceLetterObject.size() > 0)
            {
                    serviceLetterObject[0].Request_Status__c ='Delivered';
                    //serviceLetterObject[0].Request_Status__c ='Out for Delivery';
                    update serviceLetterObject;
            }
            return 'Success';
        }
        catch(System.Exception err)
        {
            return err.getMessage();
        }        
    }
    /*
    WebService static String serviceLetterConfirmLetterSignedButton(ID serviceLetterID)
    {
        try
        {
         string AramexResponse  = '';
            List<Request__c> serviceLetterObject = new List<Request__c>([select Delivery_Method__c , Request_Status__c ,Aramex_Shipment_Label__c , Shipment_Number__c from Request__c where id =: serviceLetterID]);
            // Check from the value of the record type to update
            if (serviceLetterObject.size() > 0)
            {
           
                serviceLetterObject[0].Request_Status__c ='Scheduled for Delivery';
                    //update serviceLetterObject;
                if (serviceLetterObject[0].Delivery_Method__c=='Courier'){
                    
                    string param = '';
                    
                    Aramex_Smartpaperbpm_nd.prepareShipment();
                    
                    for(Aramex_Integration__c item : Aramex_Integration__c.getAll().values()){
                        param += item.AccountCountryCode__c + '|' ;
                        param += item.AccountEntity__c + '|' ;
                        param += item.AccountNumber__c + '|' ;
                        param += item.AccountPin__c + '|' ;
                        param += item.UserName__c + '|' ;
                        param += item.Password__c + '|' ;
                        param += item.Version__c + '|';
                        param += item.AFZA_Address_Line1__c + '|';
                        param += item.AFZA_Address_Line2__c + '|';
                        param += item.AFZA_Department__c + '|';
                        param += item.AFZA_Person_Email__c + '|';
                        param += item.AFZA_Person_Name__c + '|';
                        param += item.AFZA_Person_Title__c + '|';
                        param += item.CellPhone__c + '|';
                        param += item.CompanyName__c + '|';
                        param += item.FaxNumber__c + '|';
                        param += item.PhoneNumber1__c + '|';
                        param += item.PhoneNumber1Ext__c + '|';
                        param += item.PhoneNumber2__c + '|';
                        param += item.PhoneNumber2Ext__c +'|';
                    }
                      
                    if (String.isNotBlank(param)){
                        param += serviceLetterObject[0].Name +'|';
                        param += serviceLetterObject[0].Courier_Delivery_Address__c +'|';
                        param += serviceLetterObject[0].Courier_Delivery_Country__c +'|';
                        param += serviceLetterObject[0].Courier_Delivery_City__c +'|';
                        param += serviceLetterObject[0].Courier_Delivery_Contact_Mobile__c ;
                        
                        Aramex_Smartpaperbpm_nd.WebParam = param ; 
                        Aramex_Smartpaperbpm_nd.CheckAramexShipment();
                        AramexResponse = Aramex_Smartpaperbpm_nd.stdemo;
                    }
                     // Updating the values
                    if (String.isNotBlank(AramexResponse)){
                        string ShipmentLabel = '';
                        string ShipmentNumber = '';
                        for (String token : AramexResponse.split('::::' , -2)){
                            if (token.split(':::' , -2)[0].split('::' , -2)[0] == 'shipment'){ 
                                ShipmentLabel = token.split(':::' , -2)[1].split('::' , -2)[1];
                                ShipmentNumber = token.split(':::' , -2)[0].split(':::' , -2)[0].substring(0,20);
                                ShipmentNumber = ShipmentNumber.substring(10,20);
                                
                            }
                        }
                        if (String.isNotBlank(ShipmentLabel))
                            serviceLetterObject[0].Aramex_Shipment_Label__c = ShipmentLabel ;
                        
                        if (String.isNotBlank(ShipmentNumber))
                            serviceLetterObject[0].Shipment_Number__c = ShipmentNumber ;
                    }
                    
                }
                
                Update serviceLetterObject;
            }
            
            //return 'Success';
            return AramexResponse;
        }
        catch(System.Exception err)
        {
            return err.getMessage();
        }        
    }
    */
    
    // refresh button 
    WebService static String serviceLetterRefreshCourierstatusButton(ID serviceLetterID)
    {
        try
        {
            List<Request__c> serviceLetterObject = new List<Request__c>([select Delivery_Method__c, Request_Status__c , Id, shipment_Number__c , Shipment_Status__c , Last_Courier_Update__c from Request__c where id =: serviceLetterID]);
            // Check from the value of the record type to update
            if (serviceLetterObject.size() > 0)
            {
                 String param = '' ;
                 string AramexResponse ='';
                 Map<string,Id> serviceLetterShipmentMap = new Map<string,Id>();
                 
                 Map<string,string> aramexStatusResponce = new Map<string,string>();
                 Map<string,Datetime> aramexDateResponce = new Map<string,Datetime>();
        
                for(Aramex_Integration__c item : Aramex_Integration__c.getAll().values()){
                        param += item.AccountCountryCode__c + '|' ;
                        param += item.AccountEntity__c + '|' ;
                        param += item.AccountNumber__c + '|' ;
                        param += item.AccountPin__c + '|' ;
                        param += item.UserName__c + '|' ;
                        param += item.Password__c + '|' ;
                        param += item.Version__c ;
                }
                if (String.isNotBlank(param)){
                    param +='||'+ serviceLetterObject[0].Shipment_Number__c;
                    serviceLetterShipmentMap.put(serviceLetterObject[0].Shipment_Number__c,serviceLetterObject[0].Id);
                    
                    Aramex_Smartpaperbpm.WebParam = param ; 
                    Aramex_Smartpaperbpm.CheckAramexShipment();
                    AramexResponse = Aramex_Smartpaperbpm.stdemo;
                }
                // Updating the values
                string ShipmentStatus = '';
                //system.debug('OMM TEST :: ' + AramexResponse);
                if (String.isNotBlank(AramexResponse)){
                    for (String token : AramexResponse.split('::::' , -2)){
                        if (token.split(':::' , -2)[0].split('::' , -2)[0] == 'shipment'){                  
                            string year   = token.split(':::' , -2)[2].split('::' , -2)[1].substring(0,4);
                            string month  = token.split(':::' , -2)[2].split('::' , -2)[1].substring(5,7);
                            string day    = token.split(':::' , -2)[2].split('::' , -2)[1].substring(8,10);
                            string hour   = token.split(':::' , -2)[2].split('::' , -2)[1].substring(11,13);
                            string minute = token.split(':::' , -2)[2].split('::' , -2)[1].substring(14,16);
                            string second = token.split(':::' , -2)[2].split('::' , -2)[1].substring(17,19);
                            string stDate = year + '-' + month + '-' + day + ' ' + hour + ':' + minute +  ':' + second;
                            Datetime myDate = datetime.valueOf(stDate);
                            
                            ShipmentStatus = token.split(':::' , -2)[1].split('::' , -2)[1];
                            
                            aramexStatusResponce.put(serviceLetterObject[0].Shipment_Number__c,ShipmentStatus);
                            aramexDateResponce.put(serviceLetterObject[0].Shipment_Number__c,myDate);
                        }
                    }
                    
                    if (aramexStatusResponce.containsKey(serviceLetterObject[0].shipment_Number__c))     
                        serviceLetterObject[0].Shipment_Status__c = aramexStatusResponce.get(serviceLetterObject[0].Shipment_Number__c);
                   
                    if (aramexDateResponce.containsKey(serviceLetterObject[0].shipment_Number__c))
                        serviceLetterObject[0].Last_Courier_Update__c = aramexDateResponce.get(serviceLetterObject[0].Shipment_Number__c);     
                
                
                    Update serviceLetterObject; 
                }
            
                // End of update
                
            }
            //we need here to update service letter and shipment number status 
            return 'Success';
        }
        catch(System.Exception err)
        {
            return err.getMessage();
        }
    }
       
    // OMM END

//PO 17032014
  // create confirmed letter
    WebService static String serviceLetterConfirmLetterSignedButton(ID serviceLetterID)
    {
       //String AramexResponse;

        try
        {
            List<Request__c> serviceLetterObject = new List<Request__c>([select Delivery_Method__c , Request_Status__c ,Aramex_Shipment_Label__c , Shipment_Number__c , Name,  Id,  Shipment_Status__c , Last_Courier_Update__c, 
            Courier_Delivery_Address__c, Courier_Delivery_City__c, Courier_Delivery_Country__c,
            Full_Name_English__c , Company_Name_English__c, Courier_Delivery_Contact_Mobile__c, Email__c,
            Pickup_Request_Created__c, Courier_Pickup_Date__c, Courier_Aramex_Country_Code__c
            from Request__c where id =: serviceLetterID]);
            
            // Check from the value of the record type to update
            if (serviceLetterObject.size() > 0)
            {
                //create sfparameters map
                Map<String, String> aramexCreatePickupRequestMap = new Map<String, String>();
                
                serviceLetterObject[0].Request_Status__c ='Letter Signature Completed';
                
                update serviceLetterObject;
                return 'Success';
                 
                //Mustafa Zaidi 18th June 2014
                /*serviceLetterObject[0].Request_Status__c ='Scheduled for Delivery';
                    //update serviceLetterObject;
                if (serviceLetterObject[0].Delivery_Method__c=='Courier'){

                    for(Aramex_Integration__c item : Aramex_Integration__c.getAll().values()){
                        //clientinfo
                            aramexCreatePickupRequestMap.put('AccountCountryCode__c', item.AccountCountryCode__c);
                            aramexCreatePickupRequestMap.put('AccountEntity__c', item.AccountEntity__c);
                            aramexCreatePickupRequestMap.put('AccountNumber__c', item.AccountNumber__c);
                            aramexCreatePickupRequestMap.put('AccountPin__c', item.AccountPin__c);
                            aramexCreatePickupRequestMap.put('UserName__c', item.UserName__c);
                            aramexCreatePickupRequestMap.put('Password__c', item.Password__c);
                            aramexCreatePickupRequestMap.put('Version__c', item.Version__c);     
                        //pickupaddress    
                            aramexCreatePickupRequestMap.put('AFZA_Address_Line1__c', item.AFZA_Address_Line1__c);
                            aramexCreatePickupRequestMap.put('AFZA_Address_Line2__c', item.AFZA_Address_Line2__c);
                            aramexCreatePickupRequestMap.put('AFZA_Address_City__c', item.AFZA_Address_City__c);     
                            aramexCreatePickupRequestMap.put('AFZA_Address_State__c', item.AFZA_Address_State__c);     
                            aramexCreatePickupRequestMap.put('AFZA_Address_Country__c', item.AFZA_Address_Country__c);  
                         //pickup contact 
                            aramexCreatePickupRequestMap.put('AFZA_Person_Name__c', item.AFZA_Person_Name__c);
                            aramexCreatePickupRequestMap.put('CompanyName__c', item.CompanyName__c);
                            aramexCreatePickupRequestMap.put('CellPhone__c', item.CellPhone__c);     
                            aramexCreatePickupRequestMap.put('PhoneNumber1__c', item.PhoneNumber1__c);     
                            aramexCreatePickupRequestMap.put('AFZA_Person_Email__c', item.AFZA_Person_Email__c);  
                            
                                           
                    }

                    //aramexCreatePickupRequestMap.put('Shipment_Number__c', serviceLetterObject[0].Shipment_Number__c);
                    aramexCreatePickupRequestMap.put('Name', serviceLetterObject[0].Name);


                    //delivery location
                    aramexCreatePickupRequestMap.put('Courier_Delivery_Address__c', serviceLetterObject[0].Courier_Delivery_Address__c);
                    aramexCreatePickupRequestMap.put('Courier_Delivery_City__c', serviceLetterObject[0].Courier_Delivery_City__c);
                    aramexCreatePickupRequestMap.put('Courier_Aramex_Country_Code__c', serviceLetterObject[0].Courier_Aramex_Country_Code__c);
                    
                    //contactperson
                    aramexCreatePickupRequestMap.put('Full_Name_English__c', serviceLetterObject[0].Full_Name_English__c);
                    aramexCreatePickupRequestMap.put('Company_Name_English__c', serviceLetterObject[0].Company_Name_English__c);
                    aramexCreatePickupRequestMap.put('Courier_Delivery_Contact_Mobile__c', serviceLetterObject[0].Courier_Delivery_Contact_Mobile__c);
                    aramexCreatePickupRequestMap.put('Email__c', serviceLetterObject[0].Email__c);                    
                    
                    
                    //call the aramex createpickkup webservice class
                    Aramex_Smartpaperbpm_CheckAramexShipment.CheckAramexShipment(aramexCreatePickupRequestMap);
                    //store response
                    AramexResponse = Aramex_Smartpaperbpm_CheckAramexShipment.stdemo;
                    system.debug('xml response =>' + AramexResponse);                   
                    //TODO : breakdown the response to jsontoapex
                    
                    if(AramexResponse != '' || AramexResponse != null) {
                        fromJSON obj = fromJSON.parse(AramexResponse);
                        //validations - has errors
                        if(obj.Notifications.Notification != null){
                            return obj.Notifications.Notification.Message;
                        }
                        //validations - shipment has error
                        if(obj.Shipments.ProcessedShipment.Notifications.Notification != null){
                            return obj.Shipments.ProcessedShipment.Notifications.Notification.Message;
                        }
                        
                        //updates
                        if(obj.Shipments.ProcessedShipment.HasErrors != null){
                            serviceLetterObject[0].Aramex_Shipment_Label__c = obj.Shipments.ProcessedShipment.ShipmentLabel.LabelURL;
                            serviceLetterObject[0].Shipment_Number__c = obj.Shipments.ProcessedShipment.ID;
                            //PO 6/16 setdaytoday
                            //serviceLetterObject[0].Courier_Pickup_Date__c = date.today();                            
                            Update serviceLetterObject;
                            //PO 6/16 create date pickup
                            //buttonExecutionClass.serviceLetterCreatePickupButton(serviceLetterObject.get(0).id);
                            
                            return 'Success';
                        } 
                    } 

                }*/
                
            }
            //return AramexResponse;
           return null;
        }
        catch(System.Exception err)
        {
            return err.getMessage();
        }
    }
//End confirmed letter signed



    // create pickup button 
    WebService static String serviceLetterCreatePickupButton(ID serviceLetterID)
    {
       String AramexResponse;

        try
        {
            List<Request__c> serviceLetterObject = new List<Request__c>([select Delivery_Method__c,Name, Request_Status__c , Id, shipment_Number__c , Shipment_Status__c , Last_Courier_Update__c, 
            Courier_Delivery_Address__c, Courier_Delivery_City__c, Courier_Delivery_Country__c,
            Full_Name_English__c , Company_Name_English__c, Courier_Delivery_Contact_Mobile__c, Email__c,
            Pickup_Request_Created__c, Courier_Pickup_Date__c, Courier_Aramex_Country_Code__c
            from Request__c where id =: serviceLetterID]);
            
            // Check from the value of the record type to update
            if (serviceLetterObject.size() > 0)
            {
                //create sfparameters map
                Map<String, String> aramexCreatePickupRequestMap = new Map<String, String>();
                
                for(Aramex_Integration__c item : Aramex_Integration__c.getAll().values()){
                    //clientinfo
                        aramexCreatePickupRequestMap.put('AccountCountryCode__c', item.AccountCountryCode__c);
                        aramexCreatePickupRequestMap.put('AccountEntity__c', item.AccountEntity__c);
                        aramexCreatePickupRequestMap.put('AccountNumber__c', item.AccountNumber__c);
                        aramexCreatePickupRequestMap.put('AccountPin__c', item.AccountPin__c);
                        aramexCreatePickupRequestMap.put('UserName__c', item.UserName__c);
                        aramexCreatePickupRequestMap.put('Password__c', item.Password__c);
                        aramexCreatePickupRequestMap.put('Version__c', item.Version__c);     
                    //pickupaddress    
                        aramexCreatePickupRequestMap.put('AFZA_Address_Line1__c', item.AFZA_Address_Line1__c);
                        aramexCreatePickupRequestMap.put('AFZA_Address_Line2__c', item.AFZA_Address_Line2__c);
                        aramexCreatePickupRequestMap.put('AFZA_Address_City__c', item.AFZA_Address_City__c);     
                        aramexCreatePickupRequestMap.put('AFZA_Address_State__c', item.AFZA_Address_State__c);     
                        aramexCreatePickupRequestMap.put('AFZA_Address_Country__c', item.AFZA_Address_Country__c);  
                     //pickup contact 
                        aramexCreatePickupRequestMap.put('AFZA_Person_Name__c', item.AFZA_Person_Name__c);
                        aramexCreatePickupRequestMap.put('CompanyName__c', item.CompanyName__c);
                        aramexCreatePickupRequestMap.put('CellPhone__c', item.CellPhone__c);     
                        aramexCreatePickupRequestMap.put('PhoneNumber1__c', item.PhoneNumber1__c);     
                        aramexCreatePickupRequestMap.put('AFZA_Person_Email__c', item.AFZA_Person_Email__c);  
                        
                                       
                }
                
                    //aramexCreatePickupRequestMap.put('Shipment_Number__c', serviceLetterObject[0].Shipment_Number__c);
                    aramexCreatePickupRequestMap.put('Name', serviceLetterObject[0].Name);
                    //PO 6/16
                    //Date pickupDate = serviceLetterObject[0].Courier_Pickup_Date__c;
                    //Date pickupDate = date.today().addMinutes(10);
                    //String pickupDateString = pickupDate.format();
                    //aramexCreatePickupRequestMap.put('Courier_Pickup_Date__c', pickupDateString);


                    //delivery location
                    aramexCreatePickupRequestMap.put('Courier_Delivery_Address__c', serviceLetterObject[0].Courier_Delivery_Address__c);
                    aramexCreatePickupRequestMap.put('Courier_Delivery_City__c', serviceLetterObject[0].Courier_Delivery_City__c);
                    aramexCreatePickupRequestMap.put('Courier_Aramex_Country_Code__c', serviceLetterObject[0].Courier_Aramex_Country_Code__c);
                    
                    //contactperson
                    aramexCreatePickupRequestMap.put('Full_Name_English__c', serviceLetterObject[0].Full_Name_English__c);
                    aramexCreatePickupRequestMap.put('Company_Name_English__c', serviceLetterObject[0].Company_Name_English__c);
                    aramexCreatePickupRequestMap.put('Courier_Delivery_Contact_Mobile__c', serviceLetterObject[0].Courier_Delivery_Contact_Mobile__c);
                    aramexCreatePickupRequestMap.put('Email__c', serviceLetterObject[0].Email__c);

                    
                    //serviceLetterShipmentMap.put(serviceLetterObject[0].Shipment_Number__c,serviceLetterObject[0].Id);
                    
                    
                    //call the aramex createpickkup webservice class
                    Aramex_Smartpaperbpm_CreatePickup.AramexCreatePickup(aramexCreatePickupRequestMap);
                    //store response
                    AramexResponse = Aramex_Smartpaperbpm_CreatePickup.stdemo;
                    system.debug('xml response =>' + AramexResponse);                   
                    //TODO : breakdown the response to jsontoapex
                    
                    if(AramexResponse != '' || AramexResponse != null) {
                        fromJSON obj = new fromJSON();
                        obj = fromJSON.parse(AramexResponse);
                        //validations - has errors
                        if(obj.Notifications.Notification != null){
                            return obj.Notifications.Notification.Message;
                        }
                        //validations - shipment has error
                        if(obj.ProcessedPickup.ProcessedShipments.ProcessedShipment.Notifications.Notification != null){
                            system.debug('## shipment pickup has error =>' + obj.ProcessedPickup.ProcessedShipments.ProcessedShipment.Notifications.Notification.Message);
                            return obj.ProcessedPickup.ProcessedShipments.ProcessedShipment.Notifications.Notification.Message;
                        }
                        
                        //updates
                        if(obj.ProcessedPickup.ProcessedShipments.ProcessedShipment.HasErrors == false){
                            //PO added
                            serviceLetterObject[0].Aramex_Shipment_Label__c = obj.ProcessedPickup.ProcessedShipments.ProcessedShipment.ShipmentLabel.LabelURL;
                            serviceLetterObject[0].Shipment_Number__c = obj.ProcessedPickup.ProcessedShipments.ProcessedShipment.ID;
                            serviceLetterObject[0].Courier_Pickup_Date__c = date.parse(obj.ProcessedPickup.Reference2); //pickupdate                            
                            serviceLetterObject[0].Request_Status__c = 'Scheduled for Delivery';
                            
                            serviceLetterObject[0].Pickup_Request_Created__c = true;
                            serviceLetterObject[0].Courier_Pickup_Request_Number__c = obj.ProcessedPickup.ID;
                            Update serviceLetterObject;
                            return 'Success';
                        } 
                    } 
                    
                   
            }
            //return 'Success';
           return AramexResponse;
        }
        catch(System.Exception err)
        {
            return err.getMessage();
        }
    }


//PO END       

    
     //For Mark Passport as Current Passport Method...
    WebService static String markPassportCurrent(ID passportId)
    {
        Savepoint sp;
        sp = Database.setSavepoint();
    
        try
        {
            
            //Update Current Passport Record
            Passport_History__c currentRecord = null;//new Passport_History__c();    
            currentRecord  = [select isCurrent__c from Passport_History__c where id = : passportId ];  
            
            //Only Update the Current Passport...
            if(currentRecord != null)
            {
                currentRecord.isCurrent__c = true ;
                update currentRecord;
            }
            
           
            return 'success';
            
        }catch(Exception e){system.debug(e);String errorMsg = 'error : ' + e ; Database.rollback(sp); return errorMsg ; 
        }
    }
    
    //For Mark Visa as Current Visa Method...
    WebService static String markVisaCurrent(ID visaId)
    {
        Savepoint sp;
        sp = Database.setSavepoint();
    
        try
        {
            
            //Update Current Passport Record
            Visa_History__c currentRecord  = null;//new Visa_History__c();
                
            currentRecord  = [select isCurrent__c from Visa_History__c where id = : visaId ];  
            
            if(currentRecord != null)
            {
                currentRecord.isCurrent__c = true ;
                update currentRecord;   
            }   
            
            
            return 'success';
            
        }catch(Exception e){system.debug(e);String errorMsg = 'error : ' + e ; Database.rollback(sp); return errorMsg ; 
        }
    }   
     
     /****************** For Previous Approach for the Renewal License Object ******************/       
     //For Renew License Validation Check Method....
     /*WebService static string renewLicenseValidationMethod(ID accountId)
     {
         try
         {
             List<Fines__c> fineObjectList = new List<Fines__c>([select Id,Account__c,Status__c from Fines__c where Status__c = 'Not Paid' and Account__c = : accountId]);
         
             if(fineObjectList.size() > 0)
             {
                 return 'NO';
             
             }
             else
             {
                 return 'YES';
             }
             
         }
         catch(System.Exception err)
         {
            return err.getMessage(); 
            
         }
     
     } */  
     
     /****************** For Previous Approach for the Renewal License Object ******************/   
     //For Initiating the Renew Process Method....
     /*WebService static string initiateRenewProcessMethod(ID accountId)
     {
     
         try
         {
             Account accountObject = new Account();
             
             accountObject = [select id,Renewal_Process_Start_Date__c,isTenancyCreated__c,RecordTypeId,License_Application_Step__c, License_Application_Type__c from Account where Id =: accountId];
             
             if(accountObject != null)        
             {
                 RecordType tempRecordTypeObject = new RecordType();
                 tempRecordTypeObject = [Select SobjectType, Name, IsActive, Id From RecordType where IsActive = true AND SobjectType = 'Account' AND Name = 'Renewal'];
                 
                 if(tempRecordTypeObject != null)
                 {
                     accountObject.License_Application_Step__c = 'Renewal Started';
                     accountObject.License_Application_Type__c = 'Renewal';
                     accountObject.Renewal_Process_Start_Date__c = DateTime.Now();
                     accountObject.isTenancyCreated__c = false;
                     accountObject.RecordTypeId = tempRecordTypeObject.id;
                     
                     //Now Update the record...
                     update accountObject;
                     
                     //Now Returning the value...
                     return 'Success';
                     
                 }
                 
                 return 'Some Problem occur when fetching the record type';
                 
                 
             }
             else
             {
                 return 'Account not Exist';
             }
         }
         catch(System.Exception err)
         {
             return err.getMessage(); 
         }
     
     }*/
     
    
     
}